import {
  build,
  create,
  calculate,
  payment,
  check_shipping
} from '../../../api/order';
import {
  submit,
  query
} from '../../../api/payment';
import {
  list
} from '../../../api/address';
// import { threadId } from 'worker_threads';
const util = require('../../../utils/util.js')
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    calculate: {},
    delivery: {
      title: ''
    },
    barginBuyId: '',
    groupBuyId: '',
    deliveryType: false,
    couponsType: false,
    coupons: null,
    submitType: false,
    address: null,
    order_Details: {
      address: null
    },
    sn: '',
    orderId: '',
    amount: 0,
    consignee: '',
    shippingMethods: [],
    shippingMethod: '',
    distribution: [],
    paymentVo: [],
    point: '',
    check_shippingData: [],
    payType: false,
    couponCodeName: '',
    packageType: false,
    weexDate: [{ title: '请选择配送日期' }],
    // shopType: false,
    weexTime: '',
    waterType: false,
    waterPrice: 0,
    waterStatus: false,
    bomType: 0,
    siteType: false,
    shopId: '',
    shopName: '请选择提货点',
    shopIndex: '0',
    phone: '',
    addressConsignee: '',
    addressPhone: '',
    shippingMethodType: false,
    distributionType: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {

  },
  onLoad: function (options) {
    console.log(options)

    this.loadBuild(options)

  },
  completeDelivery: function (e) {
    console.log(e)
    var _this = this
    this.data.deliveryType = false
    if (e.detail.completeDelivery.title == '普通快递') {
      _this.data.calculate.shippingMethod = 0
      _this.data.shippingMethod = 0
      _this.data.calculate.consignee = _this.data.address.consignee
      _this.data.calculate.phone = _this.data.address.phone
    } else if (e.detail.completeDelivery.title == '到店提货') {
      _this.data.calculate.shippingMethod = 1
      _this.data.shippingMethod = 1
      // _this.data.shopId = data.detail.from.id
      _this.data.calculate.consignee = _this.data.consignee
      _this.data.calculate.phone = _this.data.phone
    } else if (e.detail.completeDelivery.title == '同城配送') {
      _this.data.calculate.shippingMethod = 2
      _this.data.shippingMethod = 2
      _this.data.calculate.consignee = _this.data.address.consignee
      _this.data.calculate.phone = _this.data.address.phone
    }
    this.setData({
      delivery: e.detail.completeDelivery,
      deliveryType: _this.data.deliveryType,
      shippingMethod: _this.data.shippingMethod,
    })
  },
  deliveryClick() {
    this.data.deliveryType = true
    this.setData({
      deliveryType: this.data.deliveryType
    })
  },
  cencleDelivery() {
    this.data.deliveryType = false
    this.setData({
      deliveryType: this.data.deliveryType
    })
  },
  couponsClick() {
    if (this.data.calculate.discount == 0) {
      wx.showToast({
        title: '暂无优惠',
        icon: "none",
      })
    } else {
      this.data.couponsType = true
      this.setData({
        couponsType: this.data.couponsType
      })
    }

  },
  completecoupons: function (e) {
    console.log(e)
    this.data.couponsType = false
    this.setData({
      coupons: e.detail.completecoupons,
      couponsType: this.data.couponsType
    })
  },
  cenclecoupons() {
    this.data.couponsType = false
    this.setData({
      couponsType: this.data.couponsType
    })
  },

  check_shippingClick() {
    var _this = this
    if (_this.data.calculate.shippingMethod == 1) {
      if (_this.data.phone == '') {
        wx.showToast({
          icon: "none",
          title: '请输入提货人手机号',
        })
        return;
      }
      if (_this.data.consignee == '') {
        wx.showToast({
          icon: "none",
          title: '请输入提货人姓名',
        })
        return;
      }
      if (_this.data.shopId == '') {
        wx.showToast({
          icon: "none",
          title: '请选择提货门店',
        })
        return;
      }
    } else {
      if (util.isNull(_this.data.calculate.receiverId)) {
        wx.showToast({
          icon: "none",
          title: '请选择收货地址',
        })
        return;
      }
    }

    check_shipping(_this.data.calculate, {
      receiverId: _this.data.calculate.receiverId
    }).then(
      res => {
        console.log(res)
        if (res.data.length == 0) {
          _this.createClick()
        } else {
          _this.data.check_shippingData = res.data
          this.data.submitType = true;
          this.setData({
            submitType: this.data.submitType,
            check_shippingData: _this.data.check_shippingData
          })
        }
      }
    ).catch(error => {
      // wx.showToast({
      //         icon: "none",
      //   // title: error.content,
      // })
    })
  },
  // 创建订单
  createClick() {
    var _this = this

    if (_this.data.bomType == 1) {
      if (_this.data.weexTime == '') {
        wx.showToast({
          icon: "none",
          title: '请选择配送时间',
        })
        return
      } else {
        _this.data.calculate.weekTime = _this.data.weexTime
      }
    }
    _this.data.payType = true
    _this.setData({
      payType: _this.data.payType
    })
    if (_this.data.distributionType == true) {
      if (_this.data.address == null) {
        wx.showToast({
          title: '请选择地址',
        })
      } else {
        _this.data.shippingMethod = 0
        _this.data.calculate.shippingMethod = 0
      }
    } else if (_this.data.distributionType == false) {
      if (_this.data.phone == '') {
        wx.showToast({
          title: '请填写电话',
        })
      } else {
        _this.data.shippingMethod = 1
        _this.data.calculate.shippingMethod = 1
      }
    }
    // if(_this.data.shippingMethod == 1){
    //   _this.data.calculate.receiverId = ''
    // }else{
    //   if (util.isNull(_this.data.calculate.receiverId)) {
    //     wx.showToast({
    //       icon: "none",
    //       title: '请选择收货地址',
    //     })
    //     return;
    //   }
    // }
    _this.data.calculate.shippingMethod = _this.data.shippingMethod
    console.log(_this.data.calculate)
    create(_this.data.calculate, {
      shippingMethod: _this.data.shippingMethod,
    }).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.orderId = res.data.id
          if (res.data.paymentStatus == 1) {
            wx.redirectTo({
              url: '/pages/goods/submit/complete?id=' + _this.data.orderId,
            })
          } else {
            _this.paymentClick(res)
          }
        } else {
          _this.data.payType = false
          _this.setData({
            payType: _this.data.payType
          })
        }
      }
    ).catch(error => {
      // wx.showToast({
      //         icon: "none",
      //   // title: error.content,
      // })
      _this.data.payType = false
      _this.setData({
        payType: _this.data.payType
      })
    })
  },
  paymentClick(data) {
    var _this = this
    payment(data.data.id).then(res => {
      if (res.type == 'success') {
        console.log(res)
        _this.submitClick(res)
      } else {
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },

  submitClick(data) {
    var _this = this
    _this.data.sn = data.data.sn
    wx.showLoading({
      title: '加载中...',
    })
    submit({
      paymentPluginId: 'weixinMiniPayPlugin',
      sn: data.data.sn
    }).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.type == 'success') {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (red) {
            _this.queryClick()
          },
          'fail': function (red) {
            wx.showToast({
              icon: "none",
              title: '支付失败',
            })
            wx.redirectTo({
              url: '/pages/member/order/details?id=' + _this.data.orderId,
            })
          }
        })
      } else {
        wx.showToast({
          icon: "none",
          title: '支付失败',
        })
        wx.redirectTo({
          url: '/pages/member/order/details?id=' + _this.data.orderId,
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: '支付失败',
      })
      wx.redirectTo({
        url: '/pages/member/order/details?id=' + _this.data.orderId,
      })
    })
  },

  queryClick() {
    var _this = this
    query({
      sn: _this.data.sn
    }).then(res => {
      console.log(res)
      if (res.type == 'success') {
        wx.redirectTo({
          url: '/pages/goods/submit/complete?id=' + _this.data.orderId,
        })
      } else {
        wx.redirectTo({
          url: '/pages/goods/submit/complete?id=' + _this.data.orderId,
        })
      }
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },


  returnClick() {
    this.data.submitType = false
    this.setData({
      submitType: this.data.submitType
    })
  },
  completeClick() {
    var _this = this
    this.data.submitType = false
    _this.data.calculate.paymentVo.forEach(function (item) {
      item.chk = false,
        item.amount = 0
    })
    _this.data.calculate.itemList.forEach(function (item, index) {
      _this.data.check_shippingData.forEach(function (items) {
        if (item.productId == items.productId) {
          _this.data.calculate.itemList.splice(index, 1)
        }
      })
    })
    _this.calculateClick(_this.data.calculate)
    _this.setData({
      calculate: _this.data.calculate,
      submitType: this.data.submitType
    })
  },
  addressClick() {
    var _this = this
    wx.navigateTo({
      url: '/pages/member/address/address?type=product',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
          _this.data.address = data.data
          _this.data.calculate.address = _this.data.address.address
          _this.data.calculate.receiverId = _this.data.address.id
          _this.data.calculate.areaName = _this.data.address.areaName
          _this.data.calculate.consignee = _this.data.address.consignee
          _this.data.calculate.phone = _this.data.address.phone
          _this.setData({
            address: _this.data.address,
            calculate: _this.data.calculate
          })
          _this.calculateClick(_this.data.calculate)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
    })
  },
  loadBuild(options) {
    var _this = this
    build({
      uuid: app.globalData.uuid,
      bargainBuyId: options.bargainBuyId,
      groupBuyId: options.groupId,
      giftCardId: options.id
    }).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          _this.data.calculate = res.data.order;
          _this.data.order_Details = res.data.order;
          _this.data.order_Details.amountPaid = 0;
          if (!util.isNull(res.data.shippingMethods)) {
            _this.data.shippingMethods = res.data.shippingMethods.split(",")
            _this.data.shippingMethods.forEach(function (item) {
              if (_this.data.shippingMethods.length > 1 && item == 1) {
                _this.data.shippingMethodType = true
              }
              if (_this.data.shippingMethods.length == 1 && item == 1) {
                _this.data.distributionType = false
              }
            })
          }
          _this.setData({
            order_Details: _this.data.order_Details,
            delivery: _this.data.delivery,
            shippingMethodType:_this.data.shippingMethodType,
            distributionType:_this.data.distributionType
          })
          _this.loadList()
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  chooseLeftClick() {
    var _this = this
    this.data.distributionType = true
    _this.data.shippingMethod = 0
    _this.data.calculate.shippingMethod = 0
    _this.calculateClick(_this.data.calculate)
    this.setData({
      distributionType: this.data.distributionType
    })
  },
  chooseRightClick() {
    var _this = this
    this.data.distributionType = false
    _this.data.shippingMethod = 1
    _this.data.calculate.shippingMethod = 1
    _this.calculateClick(_this.data.calculate)
    this.setData({
      distributionType: this.data.distributionType
    })
  },
  loadList() {
    var _this = this
    var defaultAddress = []
    list({
      mchId: app.globalData.mchId
    }).then(res => {
      console.log(res)
      if (res.data.data.length > 0) {
        res.data.data.forEach(function (item) {
          if (item.isDefault == true) {
            defaultAddress.push(item)
          }
        })
      }
      console.log(this.data.address)
      if (!util.isNull(defaultAddress)) {
        _this.data.address = defaultAddress[0]
      }
      if (this.data.address != null) {
        _this.data.calculate.address = _this.data.address.address
        _this.data.calculate.receiverId = _this.data.address.id
        _this.data.calculate.areaName = _this.data.address.areaName
        _this.data.calculate.consignee = _this.data.address.consignee
        _this.data.calculate.phone = _this.data.address.phone
      }
      _this.setData({
        address: _this.data.address,
        calculate: _this.data.calculate
      })
      _this.calculateClick(_this.data.calculate)
    }).catch(error => {
      wx.showToast({
        icon: "none",
        title: error.content,
      })
    })
  },
  calculateClick(data) {
    var _this = this
    calculate(data).then(
      res => {
        console.log(res)
        if (res.type == 'success') {
          this.data.point = res.data.matchPoint
          this.data.calculate = res.data.order
          this.data.amount = res.data.amount.toFixed(2)
          this.data.bomType = res.data.bomType
          this.data.paymentVo = res.data.order.paymentVo
          // this.data.paymentVo.forEach(function(item){
          //   if (!util.isNull(item.endDate)){
          //     item.endDate = util.datetimeFormat(item.endDate)
          //   }
          // })
          if (!util.isNull(res.data.couponCodeName)) {
            _this.data.couponCodeName = res.data.couponCodeName
            _this.setData({
              couponCodeName: _this.data.couponCodeName
            })
          }
          _this.data.waterType = false
          _this.data.waterStatus = false
          // _this.data.shopType = false
          _this.data.waterPrice = 0
          res.data.order.itemList.forEach(function (item) {
            // if (item.subType == 1) {
            //   _this.data.shopType = true
            // }
            if (item.subType == 3) {
              _this.data.waterType = true
              _this.data.waterPrice += item.amount
            }
            if (item.subType == 4) {
              _this.data.waterStatus = true
            }
          })
          console.log(this.data.paymentVo)
          this.setData({
            point: this.data.point,
            calculate: this.data.calculate,
            amount: this.data.amount,
            paymentVo: this.data.paymentVo,
            // shopType: _this.data.shopType,
            waterType: _this.data.waterType,
            waterStatus: _this.data.waterStatus,
            waterPrice: _this.data.waterPrice,
            bomType: _this.data.bomType
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },
  memoClick(data) {
    var _this = this
    console.log(data)
    _this.data.calculate.memo = data.detail.value
    _this.setData({
      calculate: _this.data.calculate
    })
  },
  changeClick(data) {
    console.log(data)
    var _this = this
    var paymentPluginId = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].paymentPluginId
    if (_this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk == false) {
      if (_this.data.amount != 0) {
        if (paymentPluginId == 'waterTicketPayPlugin' || paymentPluginId == 'couponCodePayPlugin') {
          var amount = 0
          _this.data.calculate.paymentVo.forEach(function (item) {
            amount += Number(item.amount)
            item.amount = 0
            item.chk = false
          })
          amount = Number(amount) + Number(_this.data.amount)
          console.log(amount)
          console.log(_this.data.calculate.paymentVo)
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
          _this.data.amount = amount - _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount
        } else {
          if (_this.data.amount >= _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance) {
            _this.data.amount = (Number(_this.data.amount) - Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance)).toFixed(2)
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.calculate.paymentVo[data.currentTarget.dataset.index].balance
          } else {
            _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = _this.data.amount
            _this.data.amount = 0
          }
          _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = true
        }
      } else {
        _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false;
        wx.showToast({
          icon: "none",
          title: '本商品已无法抵用优惠',
        })
      }
    } else {
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].chk = false
      _this.data.amount = Number(_this.data.amount) + Number(_this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount)
      console.log(_this.data.amount)
      _this.data.amount = _this.data.amount.toFixed(2)
      _this.data.calculate.paymentVo[data.currentTarget.dataset.index].amount = 0
    }
    _this.setData({
      calculate: _this.data.calculate,
      amount: _this.data.amount
    })
  },
  packageClick() {
    this.data.packageType = !this.data.packageType
    this.setData({
      packageType: this.data.packageType
    })
  },
  cenclePackage() {
    this.data.packageType = false
    this.setData({
      packageType: this.data.packageType
    })
  },
  saveClick(data) {
    var _this = this
    console.log(data)
    _this.data.weexDate = []
    _this.data.weexTime = data.detail.weexTime
    if (data.detail.weexData.length != 0) {
      _this.data.weexDate = data.detail.weexData
    } else {
      _this.data.weexDate = [
        { title: '请选择配送日期' }
      ]
    }
    this.data.packageType = false
    this.setData({
      packageType: this.data.packageType,
      weexDate: this.data.weexDate,
      weexTime: this.data.weexTime
    })
  },
  bucketClick() {
    // if (this.data.waterType == true) {
    //   return
    // }
    this.selectComponent('#bucket').isShowClick()
  },
  productsAdd(data) {
    var _this = this
    this.selectComponent('#bucket').closeProduct()
    var itemList = data.detail
    var waterNum = 0
    var waterNumTwo = 0
    var waterNumthree = 0
    var waterType = false
    _this.data.calculate.itemList.forEach(function (item) {
      if (item.subType == 4) {
        waterNum += Number(item.quantity)
      }
      if (item.subType == 3) {
        waterNumthree += item.quantity
        waterType = true
      }
    })
    itemList.quantity = Number(waterNum)
    var itemListForm = {
      amount: itemList.price * itemList.quantity,
      availableReturnQuantity: 0,
      availableShippedQuantity: 0,
      cost: 0,
      couponCodeId: null,
      couponCodeQuantity: 0,
      createDate: null,
      discount: 0,
      id: null,
      isGift: false,
      modifyDate: null,
      name: itemList.name,
      orderId: null,
      price: itemList.price,
      productId: itemList.id,
      promotionId: null,
      quantity: itemList.quantity,
      returnQuantity: 0,
      shippedQuantity: 0,
      sn: null,
      spec: itemList.spec,
      subTotal: 0,
      subType: 3,
      thumbnail: itemList.thumbnail,
      unit: null,
      weight: 0
    }
    _this.data.calculate.itemList.forEach(function(item,index){
      if(item.subType == 3){
        _this.data.calculate.itemList.splice(index,1)
      }
    })
    _this.data.calculate.itemList.push(itemListForm)
    _this.calculateClick(_this.data.calculate)
  },
  //配送站点
  siteClick() {
    this.data.siteType = true
    this.setData({
      siteType: this.data.siteType
    })
  },
  cencleSite() {
    this.data.siteType = false
    this.setData({
      siteType: this.data.siteType
    })
  },
  completeSite(data) {
    var _this = this
    console.log(data)
    this.data.siteType = false
    this.data.shopId = data.detail.from.id
    this.data.shopName = data.detail.from.name
    this.data.shopIndex = data.detail.shopIndex
    _this.data.calculate.shopId = data.detail.from.id
    _this.data.shopAddress = data.detail.from.address
    _this.data.shopAreaName = data.detail.from.areaName
    this.setData({
      siteType: _this.data.siteType,
      shopId: _this.data.shopId,
      shopName: _this.data.shopName,
      shopIndex: _this.data.shopIndex,
      shopAddress: _this.data.shopAddress,
      shopAreaName: _this.data.shopAreaName
    })
  },
  inputConsignee(data) {
    this.data.consignee = data.detail.value
    this.data.calculate.consignee = data.detail.value
    this.setData({
      consignee: this.data.consignee
    })
  },
  input(data) {
    console.log(data)
    var _this = this
    _this.data.phone = data.detail.value
    _this.data.calculate.phone = data.detail.value
    _this.setData({
      phone: _this.data.phone
    })
  },
  dialogPhoneClick() {
    this.selectComponent('#dialogPhone').appear()
  },
    // 手机号弹窗
    savedialogPhoneClick(e) {
      console.log(e)
      this.data.phone = e.detail
      this.setData({
        phone: this.data.phone
      })
    },
})



//有压桶时，压桶也能点击
// if(waterNumthree < waterNum){
//   if(waterType == true){
//    _this.data.calculate.itemList.forEach(function (item) {
//      if (item.id == itemList.id) {
//        itemList.quantity = Number(waterNum) - Number(waterNumTwo)
//        item.quantity = Number(item.quantity) + Number(itemList.quantity)
//        _this.data.waterPrice = itemList.quantity*itemList.price
//        this.calculateClick(_this.data.calculate)
//        _this.setData({
//          waterPrice:_this.data.waterPrice
//        })
//      } else {
//        itemList.quantity = Number(waterNum) - Number(waterNumTwo)
//        var itemListForm = {
//          amount: itemList.price * itemList.quantity,
//          availableReturnQuantity: 0,
//          availableShippedQuantity: 0,
//          cost: 0,
//          couponCodeId: null,
//          couponCodeQuantity: 0,
//          createDate: null,
//          discount: 0,
//          id: null,
//          isGift: false,
//          modifyDate: null,
//          name: itemList.name,
//          orderId: null,
//          price: itemList.price,
//          productId: itemList.id,
//          promotionId: null,
//          quantity: itemList.quantity,
//          returnQuantity: 0,
//          shippedQuantity: 0,
//          sn: null,
//          spec: itemList.spec,
//          subTotal: 0,
//          subType: 3,
//          thumbnail: itemList.thumbnail,
//          unit: null,
//          weight: 0
//        }
//        _this.data.waterPrice = itemList.quantity*itemList.price
//        _this.data.calculate.itemList.push(itemListForm)
//        _this.calculateClick(_this.data.calculate)
//        _this.setData({
//          waterPrice:_this.data.waterPrice
//        })
//      }
//    })
//   }else{
//    itemList.quantity = Number(waterNum)
//    var itemListForm = {
//      amount: itemList.price * itemList.quantity,
//      availableReturnQuantity: 0,
//      availableShippedQuantity: 0,
//      cost: 0,
//      couponCodeId: null,
//      couponCodeQuantity: 0,
//      createDate: null,
//      discount: 0,
//      id: null,
//      isGift: false,
//      modifyDate: null,
//      name: itemList.name,
//      orderId: null,
//      price: itemList.price,
//      productId: itemList.id,
//      promotionId: null,
//      quantity: itemList.quantity,
//      returnQuantity: 0,
//      shippedQuantity: 0,
//      sn: null,
//      spec: itemList.spec,
//      subTotal: 0,
//      subType: 3,
//      thumbnail: itemList.thumbnail,
//      unit: null,
//      weight: 0
//    }
//    _this.data.waterPrice = itemList.quantity*itemList.price
//    _this.data.calculate.itemList.push(itemListForm)
//    _this.calculateClick(_this.data.calculate)
//    _this.setData({
//      waterPrice:_this.data.waterPrice
//    })
//   }
// }else{
//  wx.showToast({
        // icon: "none",
//    title: '压桶量请勿超过桶装水',
//  })
// }
